import os
import uuid
import json
import requests
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from pathlib import Path
from datetime import datetime
from config import Config

try:
    import tifffile
    TIFFFILE_AVAILABLE = True
except ImportError:
    TIFFFILE_AVAILABLE = False

class PhotoshopCompatibleProcessor:
    """
    完全兼容Photoshop的图层处理器
    使用TiffWriter逐个写入图层，确保PS能正确识别
    """
    
    def __init__(self):
        self.export_folder = Config.EXPORT_FOLDER
        self.upload_folder = Config.UPLOAD_FOLDER
        
    def download_image_from_url(self, url):
        """从URL下载图片"""
        try:
            response = requests.get(url, timeout=30)
            response.raise_for_status()
            return Image.open(BytesIO(response.content))
        except Exception as e:
            print(f"下载图片失败 {url}: {e}")
            # 创建明显的占位符
            return self.create_placeholder_image(200, 200, f"下载失败")
    
    def create_placeholder_image(self, width, height, text="占位符"):
        """创建明显的占位符图片"""
        img = Image.new('RGBA', (width, height), (255, 0, 0, 255))  # 红色背景
        draw = ImageDraw.Draw(img)
        
        # 黑色边框
        draw.rectangle([0, 0, width-1, height-1], outline=(0, 0, 0, 255), width=3)
        
        try:
            font = ImageFont.truetype("arial.ttf", 16)
        except:
            font = ImageFont.load_default()
        
        # 白色文字
        bbox = draw.textbbox((0, 0), text, font=font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]
        x = (width - text_width) // 2
        y = (height - text_height) // 2
        draw.text((x, y), text, fill=(255, 255, 255, 255), font=font)
        
        return img
    
    def load_original_tiff_layers(self, image_path):
        """加载原始TIFF的所有图层"""
        layers = []
        
        if not TIFFFILE_AVAILABLE:
            print("警告：tifffile未安装，只能加载第一层")
            try:
                with Image.open(image_path) as img:
                    layer = img.convert('RGBA')
                    layers.append(layer.copy())
            except Exception as e:
                print(f"加载TIFF失败: {e}")
            return layers
        
        try:
            # 使用tifffile读取原始TIFF的所有页面
            with tifffile.TiffFile(image_path) as tif:
                print(f"原始TIFF包含 {len(tif.pages)} 个页面")
                
                for i, page in enumerate(tif.pages):
                    try:
                        page_data = page.asarray()
                        
                        # 处理不同的数据类型
                        if page_data.dtype == np.uint16:
                            page_data = (page_data / 256).astype(np.uint8)
                        elif page_data.dtype != np.uint8:
                            page_data = ((page_data - page_data.min()) / 
                                       (page_data.max() - page_data.min()) * 255).astype(np.uint8)
                        
                        # 转换为PIL Image
                        if len(page_data.shape) == 2:
                            # 灰度
                            layer = Image.fromarray(page_data, mode='L').convert('RGBA')
                        elif len(page_data.shape) == 3:
                            if page_data.shape[2] == 3:
                                # RGB
                                layer = Image.fromarray(page_data, mode='RGB').convert('RGBA')
                            elif page_data.shape[2] == 4:
                                # RGBA
                                layer = Image.fromarray(page_data, mode='RGBA')
                            else:
                                # 多通道，取前3个
                                layer = Image.fromarray(page_data[:,:,:3], mode='RGB').convert('RGBA')
                        else:
                            continue
                            
                        layers.append(layer)
                        print(f"加载原始图层 {i+1}: {layer.size}")
                        
                    except Exception as e:
                        print(f"加载第{i}页失败: {e}")
                        
        except Exception as e:
            print(f"tifffile加载失败: {e}")
            # 回退到PIL
            try:
                with Image.open(image_path) as img:
                    layer = img.convert('RGBA')
                    layers.append(layer.copy())
                    print(f"PIL回退加载: {layer.size}")
            except Exception as e2:
                print(f"PIL回退也失败: {e2}")
        
        return layers
    
    def create_photoshop_compatible_tiff(self, template, regions, customization_data):
        """创建完全兼容Photoshop的多图层TIFF"""
        
        # 1. 加载原始图层
        original_layers = []
        canvas_width = template['width']
        canvas_height = template['height']
        
        if template.get('image_path'):
            image_path = template['image_path']
            if Path(image_path).is_absolute():
                template_image_path = Path(image_path)
            else:
                template_image_path = self.upload_folder / image_path
                
            if template_image_path.exists():
                print(f"加载原始TIFF: {template_image_path}")
                original_layers = self.load_original_tiff_layers(str(template_image_path))
                
                # 使用原始图片的实际尺寸
                if original_layers:
                    canvas_width, canvas_height = original_layers[0].size
                    print(f"使用原始尺寸: {canvas_width}x{canvas_height}")
        
        if not original_layers:
            # 创建空白底板
            blank = Image.new('RGBA', (canvas_width, canvas_height), (255, 255, 255, 255))
            original_layers = [blank]
            print("创建空白底板")
        
        # 2. 创建JSON图片图层
        json_layers = []
        for region_index, region_data in customization_data.get('regions', {}).items():
            elements = region_data.get('elements', [])
            
            for element_idx, element in enumerate(elements):
                try:
                    image_url = element.get('image_url')
                    if not image_url:
                        continue
                    
                    # 下载图片
                    element_image = self.download_image_from_url(image_url)
                    if not element_image:
                        continue
                    
                    # 应用用户设置
                    user_data = element.get('user_placement_data', {})
                    element_image = self._apply_user_settings(element_image, user_data)
                    
                    # 创建图层画布
                    layer_canvas = Image.new('RGBA', (canvas_width, canvas_height), (0, 0, 0, 0))
                    
                    # 获取位置
                    position = user_data.get('position', {})
                    x = int(position.get('x', 0))
                    y = int(position.get('y', 0))
                    
                    # 确保不超出边界
                    x = max(0, min(x, canvas_width - element_image.width))
                    y = max(0, min(y, canvas_height - element_image.height))
                    
                    # 粘贴到图层
                    layer_canvas.paste(element_image, (x, y), element_image)
                    json_layers.append(layer_canvas)
                    
                    print(f"创建JSON图层 {len(json_layers)}: 位置({x},{y}), 尺寸{element_image.size}")
                    
                except Exception as e:
                    print(f"处理JSON元素失败: {e}")
                    continue
        
        # 3. 使用TiffWriter逐个写入图层
        all_layers = original_layers + json_layers
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        unique_id = str(uuid.uuid4())[:8]
        filename = f"ps_compatible_{timestamp}_{unique_id}.tif"
        export_path = self.export_folder / filename
        
        print(f"开始保存 {len(all_layers)} 个图层到: {export_path}")
        
        if TIFFFILE_AVAILABLE and len(all_layers) > 1:
            return self._save_with_tiffwriter(all_layers, export_path)
        else:
            return self._save_with_pil_multipage(all_layers, export_path)
    
    def _apply_user_settings(self, image, user_data):
        """应用用户设置"""
        if image.mode != 'RGBA':
            image = image.convert('RGBA')
        
        # 尺寸调整
        dimension = user_data.get('dimension', {})
        if dimension.get('width') and dimension.get('height'):
            new_size = (int(dimension['width']), int(dimension['height']))
            image = image.resize(new_size, Image.Resampling.LANCZOS)
        
        # 旋转
        angle = user_data.get('angle_of_rotation', 0)
        if angle != 0:
            image = image.rotate(angle, expand=True, fillcolor=(0, 0, 0, 0))
        
        return image
    
    def _save_with_tiffwriter(self, layers, export_path):
        """使用TiffWriter保存，确保PS兼容性"""
        try:
            import tifffile
            
            with tifffile.TiffWriter(export_path, bigtiff=True) as tif:
                for i, layer in enumerate(layers):
                    # 转换为numpy数组
                    layer_array = np.array(layer)
                    
                    # 写入每个图层作为独立页面
                    tif.write(
                        layer_array,
                        photometric='rgb',
                        compression='lzw',
                        metadata={'Description': f'Layer {i+1}'}
                    )
                    
                    print(f"写入图层 {i+1}/{len(layers)}")
            
            print(f"TiffWriter保存完成: {export_path}")
            return export_path
            
        except Exception as e:
            print(f"TiffWriter保存失败: {e}")
            return self._save_with_pil_multipage(layers, export_path)
    
    def _save_with_pil_multipage(self, layers, export_path):
        """使用PIL多页保存"""
        try:
            if len(layers) == 1:
                layers[0].save(export_path, 'TIFF', compression='lzw')
            else:
                # 确保所有图层都是RGBA模式
                rgba_layers = []
                for layer in layers:
                    if layer.mode != 'RGBA':
                        layer = layer.convert('RGBA')
                    rgba_layers.append(layer)
                
                # 保存多页
                rgba_layers[0].save(
                    export_path,
                    'TIFF',
                    compression='lzw',
                    save_all=True,
                    append_images=rgba_layers[1:]
                )
            
            print(f"PIL多页保存完成: {export_path}")
            return export_path
            
        except Exception as e:
            print(f"PIL多页保存失败: {e}")
            raise
